package com.db.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.db.common.annotation.RequiredDept;
import com.db.common.exception.ServiceException;
import com.db.common.pojo.TreeNode;
import com.db.dao.SysDeptDao;
import com.db.pojo.SysDept;
import com.db.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    private SysDeptDao sysDeptDao;

    @RequiredDept(operation = "查询部门")
    @Transactional(readOnly = true)
    @Override
    public List<Map<String, Object>> findObjects() {
        List<Map<String, Object>> list = sysDeptDao.findObjects();
        return list;
    }

    @RequiredDept(operation = "删除部门")
    @Override
    public void deleteById(Integer id) {
        QueryWrapper<SysDept> wrapper = new QueryWrapper<>();
        wrapper.eq("parentId", id);

        Integer rows = sysDeptDao.selectCount(wrapper);
        if (rows > 0)
            throw new ServiceException("该部门有子部门,无法删除");

        sysDeptDao.deleteById(id);
    }

    @RequiredDept(operation = "查询部门树")
    @Override
    public List<TreeNode> findTree() {
        List<SysDept> sysDepts = sysDeptDao.selectList(null);

        List<TreeNode> treeNodes = new ArrayList<>();
        for (SysDept sysDept :
                sysDepts) {
            TreeNode treeNode = new TreeNode();
            treeNode.setId(sysDept.getId());
            treeNode.setName(sysDept.getName());
            treeNode.setParentId(sysDept.getParentId());
            treeNodes.add(treeNode);
        }
        return treeNodes;
    }

    @RequiredDept(operation = "新增部门")
    @Override
    public void insertObject(SysDept sysDept) {
        sysDeptDao.insert(sysDept);
    }

    @RequiredDept(operation = "更新部门")
    @Override
    public void updateObject(SysDept sysDept) {
        sysDeptDao.updateById(sysDept);
    }
}
